package com.example.springboot_demo.utils;


import com.example.springboot_demo.weixin.entity.Image;
import com.example.springboot_demo.weixin.message.ImageMessage;
import com.example.springboot_demo.weixin.utils.UploadUtil;
import com.example.springboot_demo.weixin.utils.WeiXinUtil;
import com.thoughtworks.xstream.XStream;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Date;

/**
 * 图片工具类
 */
public class ImageMessageUtil {
    /**
     * 将信息转为xml格式
     */
    public String messageToxml(ImageMessage imageMessage) {
        XStream xtream = new XStream();
        xtream.alias("xml", imageMessage.getClass());
        xtream.alias("image", new Image().getClass());
        return xtream.toXML(imageMessage);
    }

    /**
     * 封装图片消息
     *
     * @param FromUserName 发送者
     * @param ToUserName   接受者
     * @param path         图片地址
     * @return
     */
    public String initMessage(String FromUserName, String ToUserName, String path) {
        Image image = new Image();
        image.setMediaId(getMediaId(path));
        ImageMessage message = new ImageMessage();
        message.setFromUserName(FromUserName);
        message.setToUserName(ToUserName);
        message.setCreateTime(new Date().getTime());
        message.setImage(image);
        message.setMsgType("image");
        return messageToxml(message);
    }

    /**
     * 获取Media
     *
     * @return
     */
    public String getMediaId(String path) {
        String accessToken = WeiXinUtil.getAccess_Token();
        String mediaId = null;
        try {
            mediaId = UploadUtil.upload(path, accessToken, "image");
        } catch (KeyManagementException | NoSuchAlgorithmException
                | NoSuchProviderException | IOException e) {
            e.printStackTrace();
        }
        return mediaId;
    }
}